const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('🔐 初始化用户角色')
  
  try {
    const { OPENID } = cloud.getWXContext()
    
    if (!OPENID) {
      return {
        success: false,
        error: '用户身份验证失败'
      }
    }
    
    // 检查是否已经初始化过
    const existingRoles = await db.collection('user_roles').count()
    if (existingRoles.total > 0) {
      return {
        success: true,
        message: '角色已经初始化过了',
        data: {
          existingCount: existingRoles.total
        }
      }
    }
    
    // 创建默认角色
    const defaultRoles = [
      {
        roleKey: 'super_admin',
        roleName: '超级管理员',
        description: '拥有系统所有权限，可以管理用户、角色和系统设置',
        permissions: ['super_admin', 'admin', 'user_management', 'audit_management', 'data_management', 'service_management', 'order_management', 'notification_management'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        roleKey: 'admin',
        roleName: '管理员',
        description: '拥有大部分管理权限，可以管理用户和业务数据',
        permissions: ['admin', 'user_management', 'audit_management', 'service_management', 'order_management'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        roleKey: 'manager',
        roleName: '业务经理',
        description: '负责业务管理，可以审核订单和管理服务',
        permissions: ['audit_management', 'service_management', 'order_management'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        roleKey: 'auditor',
        roleName: '审核员',
        description: '负责审核工作，可以审核订单和申请',
        permissions: ['audit_management'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        roleKey: 'service_admin',
        roleName: '服务管理员',
        description: '负责服务管理，可以管理服务项目和分类',
        permissions: ['service_management'],
        createTime: new Date(),
        updateTime: new Date()
      },
      {
        roleKey: 'user',
        roleName: '普通用户',
        description: '基础用户权限，可以使用基本功能',
        permissions: ['basic'],
        createTime: new Date(),
        updateTime: new Date()
      }
    ]
    
    // 批量插入角色
    const insertPromises = defaultRoles.map(role => 
      db.collection('user_roles').add({ data: role })
    )
    
    const results = await Promise.all(insertPromises)
    
    console.log('✅ 默认角色创建成功:', results.length)
    
    // 检查当前用户是否已有权限记录
    const userPermissionResult = await db.collection('user_permissions')
      .where({ openid: OPENID })
      .get()
    
    if (userPermissionResult.data.length === 0) {
      // 为当前用户设置超级管理员权限
      await db.collection('user_permissions').add({
        data: {
          openid: OPENID,
          permissions: ['super_admin', 'admin', 'user_management', 'audit_management', 'data_management', 'service_management', 'order_management', 'notification_management'],
          role: 'super_admin',
          roleName: '超级管理员',
          roleId: results[0]._id, // 超级管理员角色ID
          createTime: new Date(),
          updateTime: new Date()
        }
      })
      
      console.log('✅ 当前用户设置为超级管理员:', OPENID)
    }
    
    return {
      success: true,
      message: '用户角色初始化成功',
      data: {
        rolesCreated: results.length,
        roleIds: results.map(r => r._id),
        currentUserSetAsAdmin: userPermissionResult.data.length === 0
      }
    }
    
  } catch (error) {
    console.error('❌ 初始化用户角色失败:', error)
    return {
      success: false,
      error: error.message || '初始化失败'
    }
  }
}
